package com.javasm.mingming.login.json;

import com.alibaba.fastjson2.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * @author javasm
 * @version 0.1
 * @className JsonLoginFilter
 * @descriptioin:
 * @date 2025/1/13 10:23
 * @since jdk11
 */
public class JsonLoginFilter extends UsernamePasswordAuthenticationFilter {

    Logger logger = LogManager.getLogger(JsonLoginFilter.class);

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")){
            throw new AuthenticationServiceException("请求方式不对,必须是POSt,你的请求方式是:"+request.getMethod());
        }
        //JSON登录
        if (!request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)){
            throw new AuthenticationServiceException("请求参数的格式不对,必须是JSON登录,你的方式是:"+request.getContentType());
        }

        //获取 用户名  密码
        //request.getParameter()//无法获取json数据,只能获取表单数据
        try {
            //从Request中 获取字节流
            ServletInputStream inputStream = request.getInputStream();
            //字节流转成字节流字符流转换对象
            InputStreamReader streamReader = new InputStreamReader(inputStream);
            //字符流
            BufferedReader reader = new BufferedReader(streamReader);
            StringBuilder json = new StringBuilder();
            String line;
            while ((line=reader.readLine()) != null){
                json.append(line).append("\n");
            }
            String jsonStr = json.toString().trim();
            logger.info(jsonStr);
            if (StringUtils.isEmpty(jsonStr)){
                throw new AuthenticationServiceException("参数为空,没有传json数据");
            }
            //json字符串转成map
            Map<String,String> map = JSONObject.parseObject(jsonStr,Map.class);
            //获取 用户名  密码
            String username = map.get("username");
            String password = map.get("password");
            //获取 验证码
            String code = map.get("code");
            Object jsonCode = request.getSession().getAttribute("json_code");
            if (jsonCode == null){
                throw new AuthenticationServiceException("未发送图片验证码");
            }
            if (code == null){
                throw new AuthenticationServiceException("未输入验证码");
            }
            String sessionCode = (String) jsonCode;
            if (!sessionCode.equals(code)){
                throw new AuthenticationServiceException("验证码错误");
            }
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,password);
            this.setDetails(request,authenticationToken);
            return this.getAuthenticationManager().authenticate(authenticationToken);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
